package com.zgyd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zgyd.Mapper.ChatHistoryMapper;
import com.zgyd.Mapper.ConversationMapper;
import com.zgyd.domin.ChatHistory;
import com.zgyd.domin.Conversation;
import com.zgyd.service.IChatHistoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.messages.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class ChatHistoryImpl extends ServiceImpl<ChatHistoryMapper, ChatHistory> implements IChatHistoryService {

    @Override
    public void saveChatHistory(String type ,String chatId) {
        Long count = lambdaQuery()
                .eq(ChatHistory::getConversationId, chatId)
                .count();
        if(count>0){
            //已经存在，不保存
            return;
        }
        String title = "对话"+chatId;
        ChatHistory chatHistory = ChatHistory.builder()
                .userId(null)//从token中获取，这里没有登录，所以先不加
                .conversationId(chatId)
                .type(type)
                .title(title)//这里截取第一次聊天的内容即可
                .createTime(LocalDateTime.now())
                .build();
        this.save(chatHistory);
    }

    @Override
    public List<String> getChatIds(String type) {
        List<ChatHistory> list = lambdaQuery()
                .eq(ChatHistory::getType,type)
                .orderByDesc(ChatHistory::getCreateTime)
                .list();
        return list.stream().map(ChatHistory::getConversationId).toList();
    }
    @Autowired
    private ConversationMapper conversationMapper;
    @Autowired
    private ChatHistoryMapper chatHistoryMapper;

    @Override
    public List<Message> findByConversationId(String chatId) {
        List<Message> messages = conversationMapper.selectObjs(new LambdaQueryWrapper<Conversation>().eq(Conversation::getConversationId, chatId));
        return messages;
    }
}